package com.wjh.garbagetype.service;

import com.wjh.garbagetype.exception.HttpRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @Description http请求服务
 * @Date 2020/4/18 15:14
 * @Created by jiahui.wu
 */
@Service
public class HttpRequestServiceImpl implements HttpRequestService {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     *  发生post请求
     * @param url
     * @param httpHeaders
     * @param params
     * @return
     */
    @Override
    public String postRequest(String url, HttpHeaders httpHeaders, MultiValueMap<String, String> params) {
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, httpHeaders);
        //执行HTTP请求
        ResponseEntity<String> exchange;
        try {
            logger.info("请求垃圾分类接口-发送post请求-url={}, httpHeader={}", url, httpHeaders.toString());
            exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            logger.info("请求垃圾分类接口-响应为-exchange={}", exchange.toString());
        } catch (RestClientException e) {
            logger.error("请求垃圾分类接口-出现异常", e);
            throw new HttpRequestException("请求垃圾分类接口-出现异常" + e.getMessage(), e);
        }
        if (exchange.getStatusCode().value() != HttpStatus.OK.value()) {
            throw new HttpRequestException("请求响应不成功-code=" + exchange.getStatusCode().value());
        }
        return exchange.getBody();
    }
}
